package com.jthinker.web.sso;

import com.jthinker.base.ex.ValidateException;
import com.jthinker.base.utils.*;
import com.jthinker.bean.UserWrapper;
import com.jthinker.service.UserService;
import com.migcomponents.migbase64.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

import static com.jthinker.base.constant.Constant.*;

/**
 * Created by chen.gang on 2014/11/8.
 */
@Controller
@RequestMapping("/sso")
public class LoginController
{
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private UserService userService;

    @RequestMapping("/validate")
    public String validate(HttpServletRequest request)
    {
        //重定向地址(空的话取首页)
        String service = StringUtils.isBlank(request.getParameter(SERVICE_NAME)) ?
                Base64.encodeToString(INDEX.getBytes(DEFAULT_CHARSET), false) :
                request.getParameter(SERVICE_NAME);
        String tgc = WebUtils.getCookieValue(request, TGC);

        if (StringUtils.isBlank(tgc))
        {
            return "redirect:/sso/gotoLogin.sso?" + SERVICE_NAME + "=" + service;
        }
        else
        {
            String tgt = SSOUtils.getTGT(tgc);

            if (StringUtils.isBlank(tgt))
            {
                return "redirect:/sso/gotoLogin.sso?" + SERVICE_NAME + "=" + service;
            }

            //票据
            String serviceTicket = SSOUtils.generateST();
            //将票据加入到缓存中
            SSOUtils.addST2Cache(serviceTicket, tgt);

            //登录前URL
            String url = new String(Base64.decode(service), DEFAULT_CHARSET);
            SSOUtils.addLogoutST(serviceTicket, tgt, url);

            return WebUtils.generateRedirectUrl(url, serviceTicket);
        }
    }

    @RequestMapping("/gotoLogin")
    public String gotoLogin()
    {
        return "/sso/login";
    }

    @RequestMapping("/login")
    @ResponseBody
    public Map<String, Object> login(HttpServletRequest request, HttpServletResponse response)
    {
        Map<String, Object> result = new HashMap<String, Object>();

        String account = request.getParameter("account");
        String passwordEncoded = request.getParameter("password");

        if (StringUtils.isBlank(account) || StringUtils.isBlank(passwordEncoded))
        {
            throw new ValidateException("账号密码不能为空!");
        }

        String rawPassword = RSAUtils.decryptStringByJs(passwordEncoded);
        String saltPassword = BaseUtils.getSaltPassword(rawPassword, account);

        UserWrapper userWrapper = userService.getUser(account, saltPassword);

        if (userWrapper == null)
        {
            result.put("code", 1);
            return result;
        }
        else
        {
            String loginTime = DateUtils.getNowTime();
            userWrapper.setLastTime(loginTime);
            userService.updateLoginTime(userWrapper.getId(), loginTime);
            LOGGER.info(" {} login {} ...", userWrapper.getAccount(), loginTime);

            String tgt = SSOUtils.generateTGT();
            String _tgt = SSOUtils.addTGT2Cache(tgt, userWrapper);

            if (StringUtils.isNotEmpty(_tgt))
            {
                result.put("code", 2);
                result.put("data", _tgt);
                return result;
            }

            //加入TGC
            String tgc = SSOUtils.generateTGC();
            SSOUtils.addTGC2Cache(tgc, tgt);
            response.addCookie(new Cookie(TGC, tgc));

            result.put("code", -1);
            return result;
        }
    }

    @RequestMapping("/invalidate")
    @ResponseBody
    public Map<String, Object> invalidate(HttpServletRequest request)
    {
        //注销前一个账号
        String tgt = request.getParameter("tgt");
        if (StringUtils.isBlank(tgt))
        {
            //注销当前账号
            String tgc = WebUtils.getCookieValue(request, TGC);
            tgt = SSOUtils.getTGT(tgc);

            if (StringUtils.isBlank(tgc))
            {
                return BaseUtils.getFailMessage("注销失败!");
            }

        }

        if (SSOUtils.invalidateTGT(tgt))
        {
            return BaseUtils.getSuccessMessage("注销成功!");
        }
        else
        {
            return BaseUtils.getFailMessage("注销失败!");
        }
    }

    @RequestMapping("/gotoRegister")
    public String gotoRegister()
    {
        return null;
    }
}
